<template>
  <div class="jindu">

    <el-form :model="form" ref="form" label-width="120px">
      <div style="width: 300px;">
        <el-form-item label="班级">
          <el-select v-model="form.classId" placeholder="请选择班级">
            <el-option v-for="item in classes" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </div>

      <el-table :data="filteredStudents" style="width: 100%">
        <el-table-column prop="name" label="姓名" width="180"></el-table-column>
        <el-table-column prop="className" label="班级" width="180"></el-table-column>
        <el-table-column prop="studentId" label="学号" width="180"></el-table-column>
      </el-table>
    </el-form>

  </div>

</template>

<script>
  export default {
    data() {
      return {
        form: {
          classId: 1, // 默认选中一班的ID  
        },
        classes: [ // 班级列表  
          { id: 1, name: '一班' },
          { id: 2, name: '二班' },
          // ...其他班级  
        ],
        students: [ // 所有班级的学生列表  
          // 一班的学生  
          { id: 1, name: '张三', className: '一班', studentId: '20230101' },
          { id: 2, name: '李四', className: '一班', studentId: '20230102' },
          { id: 3, name: '张三', className: '一班', studentId: '20230101' },
          { id: 4, name: '李四', className: '一班', studentId: '20230102' },
          { id: 5, name: '张三', className: '一班', studentId: '20230101' },
          { id: 6, name: '李四', className: '一班', studentId: '20230102' },
          // 二班的学生  
          { id: 7, name: '王五', className: '二班', studentId: '20230201' },
          { id: 8, name: '赵六', className: '二班', studentId: '20230202' },
          { id: 9, name: '王五', className: '二班', studentId: '20230201' },
          { id: 10, name: '赵六', className: '二班', studentId: '20230202' },
          { id: 11, name: '王五', className: '二班', studentId: '20230201' },
          { id: 12, name: '赵六', className: '二班', studentId: '20230202' },
          // ...其他学生  
        ],
        filteredStudents: [], // 根据选择的班级过滤后的学生列表  
      };
    },
    watch: {
      'form.classId': {
        handler(newVal) {
          this.filterStudentsByClass(newVal);
        },
        immediate: true, // 立即执行一次，以显示默认班级的学生  
      },
    },
    methods: {
      filterStudentsByClass(classId) {
        // 根据选择的班级ID过滤学生列表  
        this.filteredStudents = this.students.filter(student => student.className === this.findClassName(classId));
      },
      findClassName(classId) {
        // 根据班级ID找到班级名称  
        const classInfo = this.classes.find(cls => cls.id === classId);
        return classInfo ? classInfo.name : '';
      },
    },
    created() {
      // 在组件创建时过滤出默认班级的学生  
      this.filterStudentsByClass(this.form.classId);
    },
  };  
</script>
<style>
  .jindu {
    position: relative;
    top: 50%;
    left: 20%;
  }
</style>